package com.hmall.common.config;

import cn.hutool.core.util.ObjectUtil;
import com.hmall.common.utils.UserContext;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConversionException;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MqConfig {

    /**
     * 获取MQ消息请求头，并放到ThreadLocal中
     */
    @Bean
    public MessageConverter messageConverter() {
        return new Jackson2JsonMessageConverter() {
            @Override
            public Object fromMessage(Message message) throws MessageConversionException {
                Object userInfo = message.getMessageProperties().getHeaders().get("user-info");
                if (ObjectUtil.isNotEmpty(userInfo)) {
                    UserContext.setUser(Long.valueOf(userInfo.toString()));
                }
                return super.fromMessage(message);
            }
        };
    }
}
